//
//  NSString+Hmacsha1.m
//  lifestyle
//
//  Created by wd on 15/8/20.
//  Copyright (c) 2015年 Wei Chuang Le ,Ltd. All rights reserved.
//

#import "NSString+sha1.h"

#include "Base64.h"

#include <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (sha1)

+ (NSString *)encryptHmacsha1:(NSString *)plainText key:(NSString *)key
{
    NSData *secretData = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *clearTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    
    unsigned char cHMAC[20];
    CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], cHMAC);
    
//    NSString *hash;
//    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH];
//    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
//        [output appendFormat:@"%02x", cHMAC[i]];
//    hash = output;
//    
//    return hash;
    
    char base64Result[32];
    size_t theResultLength = 32;
    Base64EncodeData(cHMAC, 20, base64Result, &theResultLength, YES);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];
    
    NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];
    
    return base64EncodedResult;
}

@end
